/* 
Copyright (c) 2008 Delio Brignoli

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

*/

#include <Debug.h>
#include <SerialFile.h>
#define _PANIC_FUNC panic()
#define __ASSERT_USE_STDERR
#include <Assert.h>

#include <AdacTesting.h>
#include <Adac.h>

FILE debug_stream;

void panic(void) {
	while(1) {
		digitalWrite(13, HIGH);
		delay(200);
		digitalWrite(13, LOW);
		delay(200);
	}
}

int count = 0;
int result = 0;

void setup() {
  setup_serial_outfile(&debug_stream);
  dbg_init(&debug_stream, 115200, DEBUG_ANY);
  LOG_RESULT( adac_init() );
  assert(adac_get_state() == ADAC_STATE_OFF);
}

void conversion_complete(int conversion_count, void* priv) {
  count++;
  if (conversion_count == 0) {
    //Set the input the first time we are called (during prepare). It will be used for the next conversion
    adac_set_next_input(1);
  } else {
    //Set next input to a negative value will stop the conversion
    adac_set_next_input(-1);
  }
  result = adac_read_result();
}

void loop() {
  int inputs[1] = {1};

  LOG_RESULT( adac_prepare(inputs, sizeof(inputs), &conversion_complete, NULL) );
  assert(adac_get_state() == ADAC_STATE_READY);
  LOG_RESULT( adac_trigger() );
  //ASSERT(adac_get_state() == ADAC_STATE_RUNNING);
  delay(1000);
  assert(count == 2);
  count = 0;
  dbg_printf_1(info, "%d", result);
  assert(adac_get_state() == ADAC_STATE_FINISHED);
  LOG_RESULT( adac_pause() );
  assert(adac_get_state() == ADAC_STATE_FINISHED);
  LOG_RESULT( adac_stop() );
  assert(adac_get_state() == ADAC_STATE_OFF);
  delay(4000);
}
